<?php

declare(strict_types=1);

namespace app\middleware;

use core\Request;

class LogRequest
{
    private static array $buffer = [];
    private const BUFFER_SIZE = 10;

    public function handle(Request $request, \Closure $next): void
    {
        self::$buffer[] = sprintf("[%s] %s %s\n", date('Y-m-d H:i:s'), $request->getMethod(), $request->getUri());
        if (count(self::$buffer) >= self::BUFFER_SIZE) {
            $this->flush();
        }
        $next($request);
    }

    public static function flush(): void
    {
        if (self::$buffer) {
            file_put_contents(__DIR__ . '/../../runtime/logs/requests.log', implode('', self::$buffer), FILE_APPEND | LOCK_EX);
            self::$buffer = [];
        }
    }
}
